"""
批量实现excel文件转word,后期需要多写两遍
"""
import os
import pandas as pd
from docx import Document


def excel_to_word(excel_path, word_path):
    # 读取Excel文件
    df = pd.read_excel(excel_path)
    # 创建一个新的Word文档
    doc = Document()
    # 将DataFrame添加到Word文档中
    doc.add_heading('Excel内容', level=1)
    for index, row in df.iterrows():
        doc.add_paragraph(str(row))  # 将每一行作为一段添加到Word文档中
    # 保存Word文档
    doc.save(word_path)


def convert_all_excels_in_folder(folder_path, output_folder):
    # 确保输出文件夹存在
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 遍历文件夹中的所有文件
    for filename in os.listdir(folder_path):
        if filename.endswith('.xlsx') or filename.endswith('.xls'):  # 检查是否是Excel文件
            excel_path = os.path.join(folder_path, filename)
            word_filename = filename.replace('.xlsx', '.docx').replace('.xls', '.docx')
            word_path = os.path.join(output_folder, word_filename)
            print(f'Converting {filename} to {word_filename}')
            excel_to_word(excel_path, word_path)
            print(f'{filename} converted successfully.')


if __name__ == '__main__':
    # 使用示例
    folder_path = 'D:/BaiduNetdiskDownload/英语/3.大学英语'  # Excel文件所在的文件夹路径
    output_folder = 'D:/BaiduNetdiskDownload/英语/3.大学英语word'  # 输出Word文件的文件夹路径
    convert_all_excels_in_folder(folder_path, output_folder)